<template>
    <el-cascader
      v-model="currentCategory"
      :options="categoryTree"
      :props="cascaderProps"
      clearable
      @change="handleCategoryChange"
    ></el-cascader>
  </template>
  
  <script>
  export default {
    data() {
      return {
        currentCategory: [],
        categoryTree: [],
        cascaderProps: {
          value: 'id',
          label: 'name',
          children: 'children',
          checkStrictly: true
        }
      }
    },
    mounted() {
      this.loadCategories()
    },
    methods: {
      async loadCategories() {
        const { data } = await this.$http.get('/api/categories/tree')
        this.categoryTree = this.buildTree(data)
      },
      buildTree(list) {
        const map = {}
        const roots = []
        
        list.forEach(item => {
          map[item.id] = { ...item, children: [] }
          const node = map[item.id]
          item.parent_id === 0 ? 
            roots.push(node) : 
            (map[item.parent_id]?.children || []).push(node)
        })
        
        return roots
      },
      async handleCategoryChange(val) {
        if (val.length > 0) {
          const categoryId = val[val.length - 1]
          const { data } = await this.$http.get(`/api/attributes?categoryId=${categoryId}`)
          this.$emit('attributes-loaded', data)
        }
      }
    }
  }
  </script>